package it.rossignoli.enrico.app.Tesi;


import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.StaticLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import de.dfki.ccaal.gestures.IGestureRecognitionListener;
import de.dfki.ccaal.gestures.IGestureRecognitionService;
import de.dfki.ccaal.gestures.classifier.Distribution;

public class GestureActivity extends Activity
{
	
	private ListView listView;
	//private Button disconnectButton;
	View importPanel=null;
	
	
	private ArrayList<String> itemsListView;
	private String sMapping;
	private String name;
	private View ActivityView;
	
	private static boolean Riconoscimento=false;
	private boolean Learn;
	
	
	private static final int DIALOG_DISCONNECT=1;
	private static final int DIALOG_INFO_ID=3;
	
	private static final int ITEM_MENU_LEAVE=9;
	private static final int ITEM_MENU_INFO=8;
	private static final int ITEM_MENU_TRAINING = 10;
	
	
	private TextView textDialog;
	private ProgressDialog connecting;

	private ResponseReceiverGesture receiver;
	private IntentFilter filter;
	
	private static final String LOG_TAG="GestureActivity";
	
	
	//Definisco l oggetto su cui invocare il servizio
	IGestureRecognitionService recognitionService;
	String activeTrainingSet;
	
	String GestureFind;
	double GestureFindDistance;

	//implemento e definisco i metodi dicallback ala connessione e disconnessione al servizio gesti
	private final ServiceConnection serviceConnection = new ServiceConnection() 
	{

		//Metodo invocato sul bindService
		public void onServiceConnected(ComponentName className, IBinder service) 
		{
			recognitionService = IGestureRecognitionService.Stub.asInterface(service);
			try 
			{
				//recognitionService.startClassificationMode("default");
				//associo lo stub al bind fatto dalla mia applicazione
				recognitionService.registerListener(IGestureRecognitionListener.Stub.asInterface(gestureListenerStub));
			} 
			catch (RemoteException e1) 
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		//metodo chiamato dopo unbind
		public void onServiceDisconnected(ComponentName className) 
		{
			recognitionService = null;
		}
	};

	//Stub che implementa i metodi descritti dall interfaccia del listener
	IBinder gestureListenerStub = new IGestureRecognitionListener.Stub() 
	{

		
		public void onGestureLearned(String gestureName) throws RemoteException 
		{
			//Toast.makeText(GestureActivity.this, String.format("Gesture %s learned", gestureName), Toast.LENGTH_SHORT).show();
			System.err.println("Gesture %s learned");
		}

		
		public void onTrainingSetDeleted(String trainingSet) throws RemoteException 
		{
			Toast.makeText(GestureActivity.this, String.format("Training set %s deleted", trainingSet), Toast.LENGTH_SHORT).show();
			System.err.println(String.format("Training set %s deleted", trainingSet));
		}

		


		public void onGestureRecognized(final Distribution distribution) throws RemoteException 
		{
			// TODO Auto-generated method stub
			GestureFind=distribution.getBestMatch().toString();
			GestureFindDistance=distribution.getBestDistance();
			
			runOnUiThread(new Runnable() 
			{
				public void run()
				{
					//Toast.makeText(GestureActivity.this, String.format("%s: %f", distribution.getBestMatch(), distribution.getBestDistance()), Toast.LENGTH_LONG).show();
					System.err.println(String.format("%s: %f", distribution.getBestMatch(), distribution.getBestDistance()));
	
					//launchService(sMapping,GestureFindDistance);
					islearn(true);
				}
			});
			
			//gesto riconosciuto blocco la classificazione
			launchService(sMapping,GestureFindDistance);
			
		}
	};
	

	
	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.train);
        
        ActivityView=findViewById(R.layout.gesture);
        //listView=(ListView)findViewById(R.id.listGesture);
        Button ButtonGesto = (Button)findViewById(R.id.BTrain);
        //disconnectButton=(Button)findViewById(R.id.disconnect_button);
        //itemsListView=new ArrayList<String>();
        
        ButtonGesto.setOnClickListener(new OnClickListener() 
        {
			
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				try 
				{
					SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
					String Set=prefs.getString("Selected", "default").toString();
					recognitionService.startClassificationMode(Set);
				} 
				catch (RemoteException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
        
//        ButtonGesto.setOnTouchListener(new OnTouchListener() 
//        {
//			
//			
//
//			public boolean onTouch(View v, MotionEvent event) 
//			{
//				// TODO Auto-generated method stub
//				
//				if((event.getAction()==MotionEvent.ACTION_DOWN))
//				{
//					Riconoscimento=true;
//					try 
//					{
//						SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
//						String Set=prefs.getString("Selected", "default").toString();
//						recognitionService.startClassificationMode(Set);
//					} 
//					catch (RemoteException e) 
//					{
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
//				else if(event.getAction()==MotionEvent.ACTION_UP)
//				{
//					try 
//					{
//						recognitionService.stopClassificationMode();
//					} 
//					catch (RemoteException e) 
//					{
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					
//					
//					if(islearn(false)==true )
//					{
//						//CreateStub(GestureFind, GestureFindDistance);
//					}
//					
//				}
//				return false;
//			}
//		});
        
        
        SharedPreferences pref=getSharedPreferences("PREFERENCES_SMARTOBJECT", Context.MODE_PRIVATE);
		sMapping=pref.getString("COMPLETEMAPPING", null);
		
//		for(String s:sMapping.split(";"))
//		{
//			String ss[]=s.split("=");
//			if(SibIntentService.DEBUG) Log.i(LOG_TAG,ss[0]+"......."+ss[1]);
//			String sss[]=ss[0].split("#");
//			if(SibIntentService.DEBUG) Log.i(LOG_TAG,sss[0]+"......."+sss[1]);
//			itemsListView.add(sss[1]);
//		}
		
		name=pref.getString("DEVICE_NAME", "Device");
		setTitle(name);
		//disconnectButton.setText("Disconnect from "+ name);
		
		 /*
         * --------------------------------------------------------------------impostazioni ricezione risposta dal service
         */
        filter = new IntentFilter(ResponseReceiverGesture.ACTION_RESP_GESTURE);
    	filter.addCategory(Intent.CATEGORY_DEFAULT);
    	filter.addAction(ResponseReceiverGesture.ACTION_RESP_DISCONNECT);
    	filter.addAction(ResponseReceiverGesture.ACTION_LEAVEFROMSIB);
    	receiver = new ResponseReceiverGesture();
    	
    	
		
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	
//    	ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, 
//				 android.R.layout.simple_list_item_1,itemsListView);
//		 listView.setAdapter(adapter);
//		 adapter.notifyDataSetChanged();
//		 OnItemClickListener listener = new OnItemClickListener() {
//				
//				public void onItemClick(AdapterView<?> parent, View view, int position,long id) 
//				{
//					
//					String select=(String) parent.getItemAtPosition(position);
//					for(String s:sMapping.split(";"))
//					{
//						String ss[]=s.split("=");
//						String sss[]=ss[0].split("#");
//						if((sss[1].equals(select))&&(!ss[1].equals(MappingActivity.NULL_ELEMENT)))
//						{
//							Intent gestureIntent = new Intent(GestureActivity.this, SibIntentService.class);						
//					    	gestureIntent.putExtra(SibIntentService.PARAM_IN_TYPE, SibIntentService.typeIntent.GESTURE);
//					    	gestureIntent.putExtra(SibIntentService.PARAM_IN_EVENTFROMGESTURE, ss[1]);
//					        startService(gestureIntent);
//						}
//					}
//				}
//			};
//			listView.setOnItemClickListener(listener);
//			listView.setAdapter(adapter);
//			adapter.notifyDataSetChanged();
			registerReceiver(receiver, filter);
			
	    	//qui effettuo la connessione al servizio
			
			Intent bindIntent = new Intent("de.dfki.ccaal.gestures.GESTURE_RECOGNIZER");
			bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
			
    }
    
    @Override
    public void onPause()
    {
    	super.onPause();
    	unregisterReceiver(receiver);
    	
		try 
		{
			recognitionService.unregisterListener(IGestureRecognitionListener.Stub.asInterface(gestureListenerStub));
		} catch (RemoteException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		recognitionService = null;
		unbindService(serviceConnection);
		super.onPause();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        finish();
    }
    
    public void disconnectButton(View v)
    {
    	showDialog(DIALOG_DISCONNECT);
    }
    
    protected Dialog onCreateDialog(int id) 
    {
        Dialog dialog;
        switch(id) 
        {
        case DIALOG_DISCONNECT:
        	textDialog=new TextView(this);
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setTitle("Confirm disconnect?");
        	textDialog.setText("");
        	builder.setView(textDialog);
        	builder.setIcon(R.drawable.ic_launcher);
        	builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        		public void onClick(DialogInterface dialog, int id) 
        				{

        		    	connecting=ProgressDialog.show(GestureActivity.this, "Disconnect", "Disconnecting....",true, true, new DialogInterface.OnCancelListener() {

							
							public void onCancel(DialogInterface dialog) {
								toast("Interrupted");

							}

						});
        		    	
        		    	Intent intent=new Intent(GestureActivity.this, SibIntentService.class);
        				intent.putExtra(SibIntentService.PARAM_IN_TYPE,SibIntentService.typeIntent.DISCONNECT);
        		    	startService(intent);
        				}
        		});
        	builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int id) {
        	            dialog.dismiss(); // Chiudiamo la finestra di dialogo
        	            }
        	});
        	dialog = builder.create();
            break;
            
        case DIALOG_INFO_ID:
        	dialog= createInfoDialog();
        	return dialog;
        	
        default:
            dialog = null;
        }
        return dialog;
    }
    
    private Dialog createInfoDialog() {
    	// Otteniamo il riferimento al Builder
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Impostiamo il titolo, il messaggio ed una icona in chaining
		builder.setTitle(R.string.alertDialogInfo_label);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setCancelable(false);
		builder.setMessage(R.string.alertDialogInfo_message);
		// Impostiamo il pulsante di Yes con il relativo listener
		builder.setPositiveButton(R.string.alertDialogInfo_positiveLabel,
				new DialogInterface.OnClickListener() {
		
					
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
		
				});
		// Ritorniamo l'Alert creato
		return builder.create();
	}
    
    protected void onPrepareDialog(int id,Dialog dialog){
        switch(id){
        case DIALOG_DISCONNECT:
        	textDialog.setText("Disconnect from: "+name+ " ?");
        	break;
        case DIALOG_INFO_ID:
        	break;
        default:
        	break;
        }
    }

    @Override
	public boolean onCreateOptionsMenu(Menu menu) 
    {
    	super.onCreateOptionsMenu(menu);
		menu.add(Menu.FIRST, ITEM_MENU_LEAVE, 1, "Leave");
		menu.add(Menu.FIRST,ITEM_MENU_INFO,2,"Info");
		menu.add(Menu.FIRST,ITEM_MENU_TRAINING,2,"Training");
		
		return true;
	}
    
    public boolean onOptionsItemSelected (MenuItem item)
    {

    	switch (item.getItemId())
    	{

	    	case ITEM_MENU_LEAVE:
	    		myLeave();
	    		return true;
	    		
	    	case ITEM_MENU_INFO :
	    		Intent intent = new Intent(this, ListT.class);
	    		startActivity(intent);
				return true;
				
	    	case ITEM_MENU_TRAINING:
	    		Intent editGesturesIntent = new Intent().setClass(this, ProvaTrainingActivity.class);
				//editGesturesIntent.putExtra("trainingSetName", "default");
				startActivity(editGesturesIntent);
				return true;
	    		
	    		
	    	default:
            return true;
    	}
	}
    
    private void myLeave()
    {
    	Intent i = new Intent(this, SibIntentService.class);
    	i.putExtra(SibIntentService.PARAM_IN_TYPE,SibIntentService.typeIntent.LEAVE);
    	startService(i);
    	connecting=ProgressDialog.show(GestureActivity.this, "Leave", "Leaving....",true, true, new DialogInterface.OnCancelListener() {

			
			public void onCancel(DialogInterface dialog) {
				toast("Interrupted");

			}

		});
    }

    @Override
	public void onBackPressed() {
	   myLeave();
	}
    
    private void toast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }
    
    public class ResponseReceiverGesture extends BroadcastReceiver 
	{
		
	    public static final String ACTION_RESP_GESTURE = "MESSAGE_PROCESSED";
	    public static final String ACTION_RESP_DISCONNECT = "DISCONNECT_FROM_DEVICE";
	    public static final String ACTION_LEAVEFROMSIB = SibIntentService.ACTION_LEAVEFROMSIB;
	    
	    @Override
	    public void onReceive(Context context, Intent intent) 
	    {
	    	if(SibIntentService.DEBUG) Log.i(LOG_TAG,"----------------------Action response: "+intent.getAction());
	    	
	    	if(intent.getAction().equals(ACTION_RESP_GESTURE))
	    	{
		    	boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT,false);
		    	boolean c = intent.getBooleanExtra("GESTURE_CONFIRM",false);
		    	if(r)
		    	{
		    		if(c)
		    		{
		    			toast("Gesture ok!");
		    		}
		    		else
		    		{
		    			toast("Gesture failure");
		    		}
		    		
		    	}
		    	else
		    	{
		    		toast("No insert gesture!");
		    	}
	    	}
	    	else if (intent.getAction().equals(ACTION_RESP_DISCONNECT))
	    	{
	    		boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT,false);
		    	if(r)
		    	{
		    		connecting.dismiss();
		    		Intent i=new Intent(GestureActivity.this, RFIDActivity.class);
		    		startActivity(i);
		    		finish();
		    	}
		    	else
		    	{
		    		connecting.dismiss();
		    		toast("Failed disconnect!");
		    	}
	    	}
	    	else if(intent.getAction().equals(ACTION_LEAVEFROMSIB))
	    	{
	    		if(SibIntentService.DEBUG) Log.i(LOG_TAG," ACTION_LEAVEFROMSIB :");
	    		boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT,false);
	    		if(r)
	    		{
	    			connecting.dismiss();
	    			finish();
			   	}
			    else
			    {
			    	connecting.dismiss();
			    	toast("Error in leave to SIB");
			    }
	    	}
	    }
    
	}
    
	private void launchService(String sMapping, double gestureFindDistance2) 
	{
		
		try 
		{
			recognitionService.stopClassificationMode();
		} 
		catch (RemoteException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		String select=GestureFind;
		int trovato = 0;
		for(String s:sMapping.split(";"))
		{
			String ss[]=s.split("=");
			String sss[]=ss[0].split("#");
			if((sss[1].equals(select))&&(!ss[1].equals(MappingActivity.NULL_ELEMENT)))
			{
				//controllo che il gesto sia giusto

				if(GestureFindDistance <= 10)
				{
					Intent gestureIntent = new Intent(GestureActivity.this, SibIntentService.class);						
			    	gestureIntent.putExtra(SibIntentService.PARAM_IN_TYPE, SibIntentService.typeIntent.GESTURE);
			    	gestureIntent.putExtra(SibIntentService.PARAM_IN_EVENTFROMGESTURE, ss[1]);
			        startService(gestureIntent);
			        trovato=1;
			        //CreateStub(GestureFind,GestureFindDistance);
				}
				else
				{
					trovato = 2;
					//CreateStub("Gesto non Riconosciuto", GestureFindDistance);
				}
			}
		}
		switch (trovato) 
		{
		case 0:
			//gesto non presente nella lista gesti
			CreateStub("Gesto non in sib", GestureFindDistance);
			break;
		case 1:
			//gesto presente nella lista gesti
			CreateStub(GestureFind, GestureFindDistance);
			break;

		case 2:
			//gesto presente ma eseguito male
			CreateStub("Non riconosciuto...Ripetere", GestureFindDistance);
			break;


		default:
			break;
		}
		
		
	}
	
	
	private void CreateStub(String gesture, double gestureFindDistance)
	{
		
		
		
		if(importPanel==null)
		{
			importPanel = ((ViewStub) findViewById(R.id.StubViewGestoOk)).inflate();
			
			importPanel.setFocusable(true);
			importPanel.requestFocus();
//			ImageView ImageConfirm=(ImageView)importPanel.findViewById(R.id.ConfirmImage);
//			
//			
//			
//			ImageConfirm.setOnClickListener(new OnClickListener()
//			{
//				
//				public void onClick(View v) 
//				{
//					// TODO Auto-generated method stub
//					importPanel.setFocusable(false);
//					importPanel.setVisibility(View.GONE);
//					//importPanel=null;
//					//ActivityView.requestFocus();
//				}
//			});
			
		}
		
		ImageView ImageConfirm=(ImageView)importPanel.findViewById(R.id.ConfirmImage);
		
		ImageConfirm.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				importPanel.setFocusable(false);
				importPanel.setVisibility(View.GONE);
				//importPanel=null;
				//ActivityView.requestFocus();
			}
		});
		
		TextView testoGestoConferma = (TextView)importPanel.findViewById(R.id.TestoGestoOk);
		
		if((gesture.equals("Gesto non in sib"))||(gesture.equals("Non riconosciuto...Ripetere")))
		{
			testoGestoConferma.setText("Riesegui Gesto");
			ImageConfirm.setImageResource(R.drawable.x_rossa);
		}
		else
		{
			testoGestoConferma.setText(gesture+" Norma:"+gestureFindDistance);
			ImageConfirm.setImageResource(R.drawable.tick_icon);
		}

		importPanel.setVisibility(View.VISIBLE);

		
	}
	
	private boolean islearn(boolean b) 
	{
		// TODO Auto-generated method stub
		if(b==true)
		{
			Learn=true;
			return true;
		}
		
		return Learn;
		
	}
}
